import random

from Get_data.config import *
import pymongo
from Get_data.get_data_from_API import *

# 配置mongodb的信息
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]


class SaveData:
    def __init__(self):
        self.university_name = None
        self.offset = None
        self.Y = 0

    def save(self, university_name, offset, Y):
        self.university_name = university_name
        self.offset = offset
        self.Y = Y
        print("save to db")
        # data_list = GetData().get_data_from_api(self.university_name, self.offset, self.Y)
        choice_key = random.choice(KEY_LIST)
        data_list = GetData().get_data_from_api(self.university_name, self.offset, self.Y, choice_key)
        # print(data_list)
        cnt = 1
        data_len = len(data_list)
        for item in data_list:
            db[self.university_name].save(item)
            # if cnt % 10 == 0:
            #     percent = (cnt / data_len) * 100
            #     print("进度："+str(percent)+"%")
            # cnt += 1
        print("the data of " + self.university_name + " are saved! " + "offset = " + str(offset) + "  Year = " + str(
            Y) + " ，共存入" + str(len(data_list)) + "条数据！")
        # print("共存入"+str(len(data_list))+"条数据到paper_data数据库！")
        return data_len
